<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="java,杂七乱八,java集合容器," />





  <link rel="alternate" href="/atom.xml" title="Createsequence's Blog" type="application/atom+xml" />






<meta name="description" content="概述 一个 java 程序猿比较广为人知的小知识 ，是 ArrayList 和 LinkedList 最好使用迭代器删除，而不是遍历删除。 当我们尝试使用 for 循环或者 forEach 进行删除的时候，往往会出现一些意外的情况，导致集合全部删除失败。关于这点，我一直保持知其然不知其所以然的状态，刚好最近刚看完 ArrayList 和 LinkedList 的源码，今天这篇文章，就结合源码，">
<meta property="og:type" content="article">
<meta property="og:title" content="ArrayList与LinkedList遍历操作问题">
<meta property="og:url" content="http://blog.xiajibagao.top/2020/12/04/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/ArrayList%E4%B8%8ELinkedList%E9%81%8D%E5%8E%86%E6%93%8D%E4%BD%9C%E9%97%AE%E9%A2%98/index.html">
<meta property="og:site_name" content="Createsequence&#39;s Blog">
<meta property="og:description" content="概述 一个 java 程序猿比较广为人知的小知识 ，是 ArrayList 和 LinkedList 最好使用迭代器删除，而不是遍历删除。 当我们尝试使用 for 循环或者 forEach 进行删除的时候，往往会出现一些意外的情况，导致集合全部删除失败。关于这点，我一直保持知其然不知其所以然的状态，刚好最近刚看完 ArrayList 和 LinkedList 的源码，今天这篇文章，就结合源码，">
<meta property="og:locale">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201205093614320.png">
<meta property="article:published_time" content="2020-12-03T16:00:00.000Z">
<meta property="article:modified_time" content="2020-12-05T04:58:38.052Z">
<meta property="article:author" content="Createsequence">
<meta property="article:tag" content="java">
<meta property="article:tag" content="杂七乱八">
<meta property="article:tag" content="java集合容器">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://img.xiajibagao.top/image-20201205093614320.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xiajibagao.top/2020/12/04/java/集合类源码分析/ArrayList与LinkedList遍历操作问题/"/>





  <title>ArrayList与LinkedList遍历操作问题 | Createsequence's Blog</title>
  








<meta name="generator" content="Hexo 5.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Createsequence's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个努力前进的程序猿</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xiajibagao.top/2020/12/04/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/ArrayList%E4%B8%8ELinkedList%E9%81%8D%E5%8E%86%E6%93%8D%E4%BD%9C%E9%97%AE%E9%A2%98/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/Createsequence.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Createsequence's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">ArrayList与LinkedList遍历操作问题</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-04T00:00:00+08:00">
                2020-12-04
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java%E9%9B%86%E5%90%88%E5%AE%B9%E5%99%A8/" itemprop="url" rel="index">
                    <span itemprop="name">java集合容器</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3k
                </span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="概述">概述</h2>
<p>一个 java 程序猿比较广为人知的小知识 ，是 ArrayList 和 LinkedList 最好使用迭代器删除，而不是遍历删除。</p>
<p>当我们尝试使用 for 循环或者 forEach 进行删除的时候，往往会出现一些意外的情况，导致集合全部删除失败。关于这点，我一直保持知其然不知其所以然的状态，刚好最近刚看完 ArrayList 和 LinkedList 的源码，今天这篇文章，就结合源码，总结一下 ArrayList 和 LinkedList 的几种错误删除。</p>
<h2 id="一-list-集合的-fast-fail-机制">一、List 集合的 fast-fail 机制</h2>
<p>在开始前，我们需要了解一下集合的 fast-fail 机制。</p>
<p>List 接口有一个 AbstractList 抽象类，List 下的所有实现类都直接或间接的继承了它。</p>
<p>在它的成员变量中，有一个变量叫 <code>modCount</code>，当实现类进行结构性操作的时候——一般指会影响底层数据结构的操作，比如删除——就会+1。</p>
<p>在每一个迭代器创建的时候，会从外部获取当前的 <code>modCount</code>赋给迭代器的成员变量 <code>expectedModCount</code>，然后每次调用迭代器的 <code>next()</code>方法，或者其他增删方法都会比较<code>modCount</code>和<code>expectedModCount</code>是否相等，否则就会抛出 <code>ConcurrentModificationException</code> 异常。</p>
<p>这个并发修改检查可以在出现问题是时候快速抛出异常，避免可能错误的数据进入后续的操作。这也是集合操作中大部分 ConcurrentModificationException 异常的来源。</p>
<h2 id="二-arraylist-的-for-循环删除">二、ArrayList 的 for 循环删除</h2>
<p>ArrayList 的 <code>remove()</code>有根据下标删除与根据元素删除两种，后者每次删除必然需要先遍历集合，效率非常低，所以这里只讨论前者，也就是根据下标删除的方法。</p>
<h3 id="1实例">1.实例</h3>
<p>我们知道， ArrayList 底层实现是数组，他又实现了 RandomAccess 的接口，因此官方是推荐使用 for 循环去操作遍历集合的。但是<strong>当我们使用 for + 下标删除 ArrayList 中的元素时，会发生“漏删”的问题</strong>。</p>
<p>我们来模拟一下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">ArrayList&lt;String&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;(Arrays.asList(<span class="string">&quot;a&quot;</span>,<span class="string">&quot;b&quot;</span>,<span class="string">&quot;c&quot;</span>,<span class="string">&quot;d&quot;</span>));</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; list.size(); i++) &#123;</span><br><span class="line">    list.remove(i);</span><br><span class="line">&#125;</span><br><span class="line">System.out.println(list); <span class="comment">// [b, d]</span></span><br></pre></td></tr></table></figure>
<p>可见，b 和 d 被跳过了。</p>
<h3 id="2原因">2.原因</h3>
<p>我们可以看看 ArrayList 中 <code>remove()</code>方法的源码:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">remove</span><span class="params">(Object o)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (o == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> index = <span class="number">0</span>; index &lt; size; index++)</span><br><span class="line">            <span class="keyword">if</span> (elementData[index] == <span class="keyword">null</span>) &#123;</span><br><span class="line">                fastRemove(index);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> index = <span class="number">0</span>; index &lt; size; index++)</span><br><span class="line">            <span class="keyword">if</span> (o.equals(elementData[index])) &#123;</span><br><span class="line">                fastRemove(index);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们可以看到他调用了<code>fastRemove()</code>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">fastRemove</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// modCount++</span></span><br><span class="line">    modCount++;</span><br><span class="line">    <span class="keyword">int</span> numMoved = size - index - <span class="number">1</span>;</span><br><span class="line">    <span class="comment">// 是否需要移动数组</span></span><br><span class="line">    <span class="keyword">if</span> (numMoved &gt; <span class="number">0</span>)</span><br><span class="line">        <span class="comment">// 拷贝并且移动数组</span></span><br><span class="line">        System.arraycopy(elementData, index+<span class="number">1</span>, elementData, index,</span><br><span class="line">                         numMoved);</span><br><span class="line">    elementData[--size] = <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在<code>fastRemove()</code>方法里，<strong>调用了数组拷贝的方法 <code>System.arraycopy()</code>，他将删除位置后的数组整体前移一位</strong>。</p>
<p>我们来复原一下这个删除的流程：</p>
<figure>
<img src="http://img.xiajibagao.top/image-20201205093614320.png" alt="ArrayList for循环删除的流程"><figcaption aria-hidden="true">ArrayList for循环删除的流程</figcaption>
</figure>
<p><strong>简单的来说，我把 index = a 的元素删掉了，那么原本 index = a + 1 的元素就会跑到 index = a 的位置，当开始下一次循环的时候，我们以为删的是 indedx = a + 1 的元素，其实是 index = a + 2 的元素，索引发生了“偏移”，这就是“漏删”的原因。</strong></p>
<h3 id="3解决办法">3.解决办法</h3>
<p>要避免这种情况，有两种办法：</p>
<ul>
<li>每次索引偏移以后都手动把 index--；</li>
<li>想办法不让索引“偏移”，也就是不调用 <code>arraycopy()</code>方法。</li>
</ul>
<p><strong>第一种办法是在偶次操作前让 index--</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> size = list.size();</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>, j = <span class="number">0</span>; i &lt; size; i++, j++) &#123;</span><br><span class="line">    list.remove(j);</span><br><span class="line">    <span class="keyword">if</span> (j % <span class="number">2</span> == <span class="number">0</span>) &#123;</span><br><span class="line">        j--;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">System.out.println(list); <span class="comment">// []</span></span><br></pre></td></tr></table></figure>
<p>实际上，这个思路也是 ArrayList 中迭代器的 <code>remove()</code> 思路，但是用 for 循环写出来的代码非常繁琐，而且不便于理解。</p>
<p><strong>第二种办法是倒序删除</strong></p>
<p>我们回去看看 <code>fastRemove()</code>，会看到这样一段代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> numMoved = size - index - <span class="number">1</span>;</span><br><span class="line"><span class="comment">// 是否需要移动数组</span></span><br><span class="line"><span class="keyword">if</span> (numMoved &gt; <span class="number">0</span>) &#123;</span><br><span class="line">    ... ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>实际上，<code>numMoved = szie - 1 - index</code>决定了是否需要移动数组，也就是说，我们传入的 <code>index</code> 只要大于等于 <code>size</code>，就不会引起下标，那样我们可以倒序删除：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = list.size() - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">    list.remove(i);</span><br><span class="line">&#125;</span><br><span class="line">System.out.println(list); <span class="comment">// []</span></span><br></pre></td></tr></table></figure>
<h2 id="三-arraylist-的-foreach-删除">三、ArrayList 的 forEach 删除</h2>
<h3 id="1实例">1.实例</h3>
<p>先说问题，ArrayList 在使用 <code>forEach()</code>循环删除的时候会抛异常：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">ArrayList&lt;String&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;(Arrays.asList(<span class="string">&quot;a&quot;</span>,<span class="string">&quot;b&quot;</span>,<span class="string">&quot;c&quot;</span>,<span class="string">&quot;d&quot;</span>));</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    list.forEach(list::remove);</span><br><span class="line">&#125; <span class="keyword">catch</span> (ConcurrentModificationException e) &#123;</span><br><span class="line">    System.out.println(list); <span class="comment">// [b, c, d]</span></span><br><span class="line">    e.printStackTrace(); <span class="comment">// ConcurrentModificationException</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在删除第二个元素的时候，这段代码抛异常了。</p>
<h3 id="2原因">2.原因</h3>
<p>ArrayList 的 forEach 方法来自 Collection 的父接口 Iterable，Iterable 的默认显示方式是增强 for 循环，而 ArrayList 重写了这个方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">forEach</span><span class="params">(Consumer&lt;? <span class="keyword">super</span> E&gt; action)</span> </span>&#123;</span><br><span class="line">    Objects.requireNonNull(action);</span><br><span class="line">    <span class="comment">// 获取当前 modCount</span></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> expectedModCount = modCount;</span><br><span class="line">    <span class="meta">@SuppressWarnings(&quot;unchecked&quot;)</span></span><br><span class="line">    <span class="keyword">final</span> E[] elementData = (E[]) <span class="keyword">this</span>.elementData;</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> size = <span class="keyword">this</span>.size;</span><br><span class="line">    <span class="comment">// 每次循环开始前检查 modCount</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i=<span class="number">0</span>; modCount == expectedModCount &amp;&amp; i &lt; size; i++) &#123;</span><br><span class="line">        action.accept(elementData[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (modCount != expectedModCount) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>forEach()</code>开始就使用 <code>expectedModCount</code> 记录了方法开始时的 <code>modCount</code>，然后每次循环的时候和循环结束的时候都会判断 <code>modCount == expectedModCount</code>， 我们回头看看 ArrayList 的 <code>remove()</code>方法，会看到在 <code>fastRemove()</code>中开始就让 <code>modCount++</code>了，因此我们不难推断出这整个流程：</p>
<ul>
<li><code>forEach()</code>，方法调用，此时<code>expectedModCount = modCount = 0</code>；</li>
<li>进入 for 循环，判断 <code>expectedModCount = modCount</code>通过，进行第一次遍历</li>
<li><code>action.accept()</code>中我们使用 lambda 表达式传入了 <code>remove()</code>方法，此时删除了第一个元素，并且 <code>modCount++</code>。现在 <code>modCount=1</code></li>
<li>判断<code>expectedModCount = modCount</code>不通过，跳出循环</li>
<li>判断 <code>modCount != expectedModCount</code>通过，抛出异常</li>
</ul>
<p>也就说，<strong>不止是删除，所有会导致 <code>modCount</code>增加的方法，都不可以在 <code>forEach()</code>中使用</strong>。</p>
<p>我们可以使用 <code>add()</code>检验看看：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">ArrayList&lt;String&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;(Arrays.asList(<span class="string">&quot;a&quot;</span>,<span class="string">&quot;b&quot;</span>,<span class="string">&quot;c&quot;</span>,<span class="string">&quot;d&quot;</span>));</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    list.forEach(list::add); <span class="comment">// [a, b, c, d, a]</span></span><br><span class="line">&#125; <span class="keyword">catch</span> (ConcurrentModificationException e) &#123;</span><br><span class="line">    System.out.println(list);</span><br><span class="line">    e.printStackTrace(); <span class="comment">// ConcurrentModificationException</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="四-arraylist-的迭代器删除">四、ArrayList 的迭代器删除</h2>
<p>使用<strong>迭代器的方法删除是没问题的，但是如果在迭代器迭代过程中，调用了非迭代器的方法，就会出问题</strong>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">ArrayList&lt;String&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;(Arrays.asList(<span class="string">&quot;a&quot;</span>,<span class="string">&quot;b&quot;</span>,<span class="string">&quot;c&quot;</span>,<span class="string">&quot;d&quot;</span>));</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    Iterator&lt;String&gt; iterator = list.iterator();</span><br><span class="line">    <span class="keyword">while</span> (iterator.hasNext()) &#123;</span><br><span class="line">        String s = (String) iterator.next();</span><br><span class="line">        <span class="comment">// 使用非iterator的方法删除</span></span><br><span class="line">        list.remove(s);</span><br><span class="line">    &#125;</span><br><span class="line">&#125; <span class="keyword">catch</span> (ConcurrentModificationException e) &#123;</span><br><span class="line">    System.out.println(list); <span class="comment">// [b, c, d]</span></span><br><span class="line">    e.printStackTrace(); <span class="comment">// ConcurrentModificationException</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以看到抛异常了，但是把 <code>list.remove()</code>换成 <code>iterator.remove()</code>就没问题。</p>
<p>我们可以看看 <code>iterator.remove()</code>的源码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">remove</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (lastRet &lt; <span class="number">0</span>)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException();</span><br><span class="line">    checkForComodification();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 调用外部的remove方法</span></span><br><span class="line">        ArrayList.<span class="keyword">this</span>.remove(lastRet);</span><br><span class="line">        cursor = lastRet;</span><br><span class="line">        lastRet = -<span class="number">1</span>;</span><br><span class="line">        <span class="comment">// 获取最新的 modCount</span></span><br><span class="line">        expectedModCount = modCount;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IndexOutOfBoundsException ex) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>明显的，相比直接调用外部 <code>remove()</code> ，迭代器内部的 <code>remove()</code>在调用外部的 <code>remove()</code>以后，又更新了 <code>expectedModCount</code>，这个 <code>expectedModCount</code>是个迭代器内部的成员变量，在构造方法执行的时候从外部获取 <code>modCount</code>并赋给他，每一次调用迭代器的 <code>next()</code>方法前都会比较 <code>expectedModCount</code> 和 <code>modCount</code>，如果不相等就会抛异常。</p>
<p>至此问题就明了了，<strong>当我们不使用迭代器内部的 <code>remove()</code>删除节点的时候，<code>modCount</code>更新了，但是<code>expectedModCount</code>，因而在迭代第二个元素的时候就会抛出 ConcurrentModificationException 异常</strong>。</p>
<p>换句话说，和 <code>forEach()</code>一样，并不是只有 <code>remove()</code>才会引起如此问题，<strong>在迭代器迭代过程中，调用任何外部会导致 <code>modCount</code>改变的方法都会使其抛异常。</strong></p>
<h2 id="五-linkedlist-的-for-循环删除">五、LinkedList 的 for 循环删除</h2>
<p>LinkedList 的 for 循环删除也会导致“漏删”</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">LinkedList&lt;String&gt; list = <span class="keyword">new</span> LinkedList&lt;&gt;(Arrays.asList(<span class="string">&quot;a&quot;</span>,<span class="string">&quot;b&quot;</span>,<span class="string">&quot;c&quot;</span>,<span class="string">&quot;d&quot;</span>));</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; list.size(); i++) &#123;</span><br><span class="line">    list.remove(i);</span><br><span class="line">&#125;</span><br><span class="line">System.out.println(list); <span class="comment">// [b, d]</span></span><br></pre></td></tr></table></figure>
<p>和 ArrayList 的 for 循环删除出错的原因一样，也是因为索引发生了“偏移”。但是和 ArrayList 不一样的是，由于 LinkedList 底层实现是链表，所以他不是通过 <code>arraycopy()</code>方法，而是直接解除了前后节点的引用关系：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> E <span class="title">remove</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">    checkElementIndex(index);</span><br><span class="line">    <span class="keyword">return</span> unlink(node(index));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function">E <span class="title">unlink</span><span class="params">(Node&lt;E&gt; x)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// assert x != null;</span></span><br><span class="line">    <span class="keyword">final</span> E element = x.item;</span><br><span class="line">    <span class="keyword">final</span> Node&lt;E&gt; next = x.next;</span><br><span class="line">    <span class="keyword">final</span> Node&lt;E&gt; prev = x.prev;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (prev == <span class="keyword">null</span>) &#123;</span><br><span class="line">        first = next;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        prev.next = next;</span><br><span class="line">        x.prev = <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (next == <span class="keyword">null</span>) &#123;</span><br><span class="line">        last = prev;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        next.prev = prev;</span><br><span class="line">        x.next = <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    x.item = <span class="keyword">null</span>;</span><br><span class="line">    size--;</span><br><span class="line">    modCount++;</span><br><span class="line">    <span class="keyword">return</span> element;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>解决方法和 ArrayList 一样，只要避免循环中索引“偏移”即可，ArrayList 中<strong>手动 index-- 和倒序删除两种办法对他同样适用</strong>。</p>
<h2 id="六-linkedlist-的-foreach-删除">六、LinkedList 的 forEach 删除</h2>
<p>ArrayList 中的 <code>forEach()</code>是重写了 Iterable 接口的 <code>forEach()</code>方法，但是 LinkedList 中没有重写，所以 LinkedList 的 <code>forEach()</code> 使用的仍然还是 Iterable 接口中提供的实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">default</span> <span class="keyword">void</span> <span class="title">forEach</span><span class="params">(Consumer&lt;? <span class="keyword">super</span> T&gt; action)</span> </span>&#123;</span><br><span class="line">    Objects.requireNonNull(action);</span><br><span class="line">    <span class="keyword">for</span> (T t : <span class="keyword">this</span>) &#123;</span><br><span class="line">        action.accept(t);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当我们使用增强 for 循环遍历数组的时候，最终编译以后得到的是 for + 下标的普通 for 循环，而遍历集合则会编译为迭代器版的循环。因此：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// forEach</span></span><br><span class="line">list.forEach(list::remove);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 增强for</span></span><br><span class="line"><span class="keyword">for</span> (T t : list) &#123;</span><br><span class="line">    list.remove(t);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 迭代器</span></span><br><span class="line">Iterator&lt;T&gt; iterator = list.listIterator();</span><br><span class="line"><span class="keyword">while</span> (iterator.hasNext()) &#123;</span><br><span class="line">    list.remove(iterator.next());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面三种写法是等价的。在 LinkedList 中， forEach 遍历和迭代器遍历是等价的，前者到最后还是用的迭代器。而实际上，当我们看到迭代器里面的 <code>list.remove()</code>就应该明白 LinkedList 的 <code>forEach()</code>为什么会抛异常了。</p>
<p>和 ArrayList 的迭代器删除一样，<strong>由于调用的是外部的 <code>remove()</code>导致<code>modCount</code>改变，而<code>expectedModCount</code>没有改变，因此在调用<code>next()</code>的时候会因为过不了 <code>expectedModCount = modCount</code>而抛出 ConcurrentModificationException 异常</strong>。</p>
<h2 id="七-总结">七、总结</h2>
<p><strong>为什么有时候会抛出 ConcurrentModificationException 异常？</strong></p>
<p>List 集合中存在并发修改检查机制，AbstractList 提供 <code>modCount</code>字段，当使用 <code>add()</code>或者 <code>remove()</code>这样结构性操作的方法时，会让 <code>modCount + 1</code>。List 实现类的迭代器在创建的时候，都会使用成员变量 <code>expectedModCount</code> 记录当前的 <code>modCount</code>，<strong>每次调用 <code>next()</code>的时候都会检查最新的 <code>modCount</code>与 <code>expectedModCount</code>是否相等，否则就抛出 Con0currentModificationException 异常</strong>。</p>
<p>因此，只有调用迭代器内部提供的方法，才会同步更新<code>expectedModCount</code>，否则只会更新<code>modCount</code>。<strong>所以 ArrayList 与 LinkedList 在迭代器迭代过程中增删会抛异常</strong>。</p>
<p>ArrayList 重写了 <code>forEach()</code>方法，从增强 for 改为了普通的 for 循环，但是<strong>在方法最开始也记录了<code>modCount</code>，每次循环都会对比，因此也会因为在循环中改变了 <code>modCount</code>而抛异常</strong>。</p>
<p>LinkedList 未重写 <code>forEach()</code>方法，<strong>底层仍然使用增强 for，编译后还是迭代器，因此抛异常的原因同迭代器中操作</strong>。</p>
<p><strong>为什么普通 for 循环删除会“漏删”？</strong></p>
<p>ArrayList 的删除底层是使用 <code>arraycopy</code>方法生成了一个新数组，新数组上被删除节点以后的全部元素都会前移一位，导致了索引的“偏移”，因此删除了 a，那 a+1 的元素就会调到 a 的位置，下一次删除 a + 1 实际上是删除 a + 2，因此 a + 1 就被跳过了。</p>
<p>LinkedList 是链表，但是删除一个节点也会导致后一个节点“补到”被删除节点的下标对应的位置，因此同样也会因为索引“偏移”而出现“漏删”的情况。</p>
<p>解决方法是有两种，一种是在删除元素以后让索引继续指向当前位置，另一种是倒序删除。</p>
<p>其实如果添加元素的话也会有问题，虽然能够添加成功，但是不会按照指定的顺序插入，这也是因为上面这个原因。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/%E6%9D%82%E4%B8%83%E4%B9%B1%E5%85%AB/" rel="tag"># 杂七乱八</a>
          
            <a href="/tags/java%E9%9B%86%E5%90%88%E5%AE%B9%E5%99%A8/" rel="tag"># java集合容器</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/12/03/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E5%9B%9B%EF%BC%89%EF%BC%9ALinkedList/" rel="next" title="java集合源码分析（四）：LinkedList">
                <i class="fa fa-chevron-left"></i> java集合源码分析（四）：LinkedList
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/12/07/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E4%BA%94%EF%BC%89%EF%BC%9AMap%E4%B8%8EAbstractMap/" rel="prev" title="java集合源码分析（五）：Map与AbstractMap">
                java集合源码分析（五）：Map与AbstractMap <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/Createsequence.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7Carchive">
              
                  <span class="site-state-item-count">89</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A6%82%E8%BF%B0"><span class="nav-text">概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80-list-%E9%9B%86%E5%90%88%E7%9A%84-fast-fail-%E6%9C%BA%E5%88%B6"><span class="nav-text">一、List 集合的 fast-fail 机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C-arraylist-%E7%9A%84-for-%E5%BE%AA%E7%8E%AF%E5%88%A0%E9%99%A4"><span class="nav-text">二、ArrayList 的 for 循环删除</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E5%AE%9E%E4%BE%8B"><span class="nav-text">1.实例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E5%8E%9F%E5%9B%A0"><span class="nav-text">2.原因</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E8%A7%A3%E5%86%B3%E5%8A%9E%E6%B3%95"><span class="nav-text">3.解决办法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%89-arraylist-%E7%9A%84-foreach-%E5%88%A0%E9%99%A4"><span class="nav-text">三、ArrayList 的 forEach 删除</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E5%AE%9E%E4%BE%8B"><span class="nav-text">1.实例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E5%8E%9F%E5%9B%A0"><span class="nav-text">2.原因</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9B%9B-arraylist-%E7%9A%84%E8%BF%AD%E4%BB%A3%E5%99%A8%E5%88%A0%E9%99%A4"><span class="nav-text">四、ArrayList 的迭代器删除</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%94-linkedlist-%E7%9A%84-for-%E5%BE%AA%E7%8E%AF%E5%88%A0%E9%99%A4"><span class="nav-text">五、LinkedList 的 for 循环删除</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%AD-linkedlist-%E7%9A%84-foreach-%E5%88%A0%E9%99%A4"><span class="nav-text">六、LinkedList 的 forEach 删除</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%83-%E6%80%BB%E7%BB%93"><span class="nav-text">七、总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Createsequence</span>

  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  <!-- 引入目录截取js -->
  <script type="text/javascript" src="/js/src/custom/custom.js"></script>
</body>
</html>
